#include "thread_pool.h"


int break_point(task_t* task){
    printf("break_point\n");
    
    int len_ed;
    recvn(task->peerfd, &len_ed, sizeof(len_ed));

    int ret = -1;
    int pipefds[2];
    int total = len_ed;
    int filelength = 0;
    int filefd = open(task->data, O_RDONLY);

    struct stat st;
    bzero(&st, sizeof(st));
    fstat(filefd, &st);
    filelength = st.st_size;

    printf("filelength:%d\n", filelength);
    printf("len_ed:%d\n", len_ed);

    sendn(task->peerfd, &filelength, sizeof(filelength));
    if(len_ed == filelength){
        printf("file is exist.\n");
        return 0;
    } 

    // 移动文件指针到指定位置
    lseek(filefd, len_ed, SEEK_SET);

    // 创建管道
    if (pipe(pipefds) == -1) {
        perror("pipe_err");
    }

    while (total < filelength) {
        ret = splice(filefd, NULL, pipefds[1], NULL, 4096, SPLICE_F_MORE);
        if (ret < 0) {
            perror("splice file to pipe");
            break;
        }
        if (ret == 0) {
            // 文件已读取完毕
            break;
        }

        total += ret;

        ret = splice(pipefds[0], NULL, task->peerfd, NULL, 4096, SPLICE_F_MORE);
        if (ret < 0) {
            perror("splice pipe to socket");
            break;
        }
        if (ret == 0) {
            // 客户端可能断开连接
            break;
        }
    }

    close(pipefds[0]);
    close(pipefds[1]);

    if (total < filelength) {
        printf("File transfer interrupted, total bytes sent: %d\n", total);
    } else {
        printf("File transfer complete, total bytes sent: %d\n", total);
    }
}

